﻿/**
 * File相关方法
 * @namespace File
 * @name core.File
 * @static
 */
core.File = {};
/**
 * 文件异步加载器
 * @function
 * @name core.File.loader
 * @grammar core.File.loader()
 *
 * @returns {Function} .load()方法
 */
core.File.loader = function () {
  var dc = document;

  function createScript(url, callback) {
    url = url.trim();
    var urls = url ? url.replace(/,\s+$/ig, ",").split(",") : [];
    var completeNum = 0, ie6 = window.VBArray && !window.XMLHttpRequest;
    callback = callback || function () {
    };
    if (urls.length === 0) {
      callback instanceof Function && callback();
    } else {
      for (var i = 0; i < urls.length; i++) {
        (function (_path) {
          if (window.Loader && window.Loader.c) {
            _path += (_path.indexOf("?") !== -1 ? "&" : "?") + window.Loader.c;
          }
          if (core.File.Js.cache(_path)) {
            (function () {
              if (core.File.Js.cache(_path) === "loaded") {
                completeNum++;
                completeNum >= urls.length ? callback() : "";
              } else {
                window.setTimeout(arguments.callee, 200);
              }
            })();
          } else {
            core.File.Js.cache(_path, "loading");
            var _script = dc.createElement("script");
            _script.type = "text/javascript";
            if (_script.readyState) {
              _script.onreadystatechange = function () {
                if (ie6 && !this.getAttribute("initialized")) {
                  dc.getElementsByTagName("head")[0].appendChild(_script);
                  this.setAttribute("initialized", true);
                }
                if (this.readyState == "loaded" || this.readyState == "complete") {
                  core.File.Js.cache(_path, "loaded");
                  this.onreadystatechange = null;
                  completeNum++;
                  completeNum >= urls.length ? callback() : "";
                }
              };
              _script.src = _path;
              !ie6 && dc.getElementsByTagName("head")[0].appendChild(_script);
            } else {
              _script.src = _path;
              _script.onload = function () {
                core.File.Js.cache(_path, "loaded");
                completeNum++;
                completeNum >= urls.length ? callback() : "";
              };
              dc.getElementsByTagName("head")[0].appendChild(_script);
            }
          }
        })(urls[i]);
      }
    }
  }

  function createLink(url, callback) {
    url = url.trim();
    var urls = url ? url.replace(/,\s+$/ig, ",").split(",") : [];
    var links = [];
    callback = callback || function () {
    };
    if (urls.length === 0) {
      callback instanceof Function && callback();
    } else {
      for (var i = 0; i < urls.length; i++) {
        links[i] = dc.createElement("link");
        links[i].rel = "stylesheet";
        links[i].href = urls[i];
        dc.getElementsByTagName("head")[0].appendChild(links[i]);
      }
      callback instanceof Function ? callback() : "";
    }
  }

  return {
    load: function (option, callback) {
      var _type = "", _url = "";
      var _callback = callback;
      option.type ? _type = option.type : "";
      option.url ? _url = option.url : "";
      typeof option.filtration == "boolean" ? filtration = option.filtration : "";
      switch (_type) {
        case "js":
        case "javascript":
          createScript(_url, _callback);
          break;
        case "css":
          createLink(_url, _callback);
          break;
      }
      return this;
    }
  }
};
core.File.Js = {
  _cache: {},
  cache: function (name, value) {
    if (!name) throw new Error('core.File.Js.cache -> name is null.');
    if (value) {
      //set value
      this._cache[name] = value;
      return this;
    } else {
      //get value
      return this._cache[name] || null;
    }
  },
  load: function (namelist, callback) {
    var that = this;
    if (!namelist) return that;
    var arr = namelist.split(",").map(function (v) {
      return v.indexOf("http") === 0 ? v : Loader.s + Loader.p + 'js/' + v;
    });
    core.File.loader().load({
      type: "js",
      url: arr.join(",")
    }, callback);
    return that;
  },
  loadMoudle: function (moudle, namelist, callback) {
    var that = this, url;
    if (!moudle || !namelist) return that;
    if (moudle === "v8") {
      url = core.Env.sRoot + "js/v8/";
    } else {
      url = core.Env.sRoot + moudle + "/beta2/js/";
    }
    namelist = namelist.split(",").map(function (v) {
      if (v.indexOf("http") === 0) {
        return v;
      } else {
        return url + v;
      }
    }).join(",");
    that.load(namelist, callback);
    return that;
  }
};
core.File.loadImage = function (imageUrl, callback) {
  var img = new Image();
  img.src = imageUrl;
  if (img.complete) { //如果图片已经存在于浏览器缓存，直接调用回调函数
    callback && callback.apply(img);
    return; // 直接返回，不用再处理onload事件
  }
  img.onload = function () { //图片下载完毕时异步调用callback函数。
    callback && callback.apply(img);//将回调函数的this替换为Image对象
  };
};
